import { Editor } from "react-draft-wysiwyg";
import { EditorState, convertToRaw, ContentState } from 'draft-js';

import "react-draft-wysiwyg/dist/react-draft-wysiwyg.css";
import './index.less'
import draftToHtml from 'draftjs-to-html';
import htmlToDraft from 'html-to-draftjs';
import { useContext, useEffect, useRef, useState } from "react";
import { message } from "antd";
import { AppContext, isExternal } from "..";
interface RichTextProps {
  value?: string
  action?: string
  fileUploadData?: any
  disabled?:boolean
  onChange?: (html: string) => any
}
const RichText = ({ disabled,action, value, fileUploadData, onChange }: RichTextProps) => {
  const { upload, commonHeaders, richText, apiPrefix } = useContext(AppContext)


  const editorRef = useRef(null)
  const [editorState, setEditorState] = useState<any>(null)
  useEffect(() => {
    if (typeof value === 'string') {
      const contentBlock = htmlToDraft(value);
      if (contentBlock) {

        const contentState = ContentState.createFromBlockArray(contentBlock.contentBlocks);
        const editorState = EditorState.createWithContent(contentState);

        //   setEditorState(editorState)
        // editorRef.current = editorState
        setEditorState(editorState)
        //   this.state = {
        //     editorState,
        //   }
      }
    }

  }, [value])
  const onEditorStateChange = (v) => {
    // debugger

    // editorRef.current = v
    // setEditorState(v)
    // console.log(
    //     'draftToHtml(convertToRaw(editorState.getCurrentContent()))',

    // )
    //   const html = draftToHtml(convertToRaw(editorState.getCurrentContent()))
    onChange && onChange(editorState)
    setEditorState(v)
  }
  const uploadImageCallBack = (file) => {
    return new Promise(
      (resolve, reject) => {
        let formData = new FormData()
        formData.append('file', file)
        if (fileUploadData) {
          Object.keys(fileUploadData).forEach(key => {
            formData.append(key, fileUploadData[key])
          })
        }
        if (!action) {
          action = upload.action
        }
        if (!isExternal(action)) {
          action = apiPrefix + action
        }
        fetch(action, {
          method: 'POST',
          headers: {
            ...commonHeaders
          },
          body: formData,
        }).then(res => {
          return res.json()
        }).then(res => {
          if (res.code != 200) {
            message.error('图片上传失败', 2)
            reject(res)
          } else {
            if (richText) {
              const { fileUrlResultFormat } = richText
              const url = fileUrlResultFormat(res)
              resolve({ data: { link: url } })
            }

          }

        }).catch(err => {
          reject(err)
        })
      }
    )
  }

  return <Editor
    localization={{
      locale: 'zh',
    }}
    readOnly={disabled}
    editorState={editorState}
    onEditorStateChange={onEditorStateChange}
    toolbarClassName="toolbarClassName"
    wrapperClassName="wrapperClassName"
    editorClassName="rich-text-container"
    toolbar={{
      image: {
        urlEnabled: true,
        uploadEnabled: true,
        alignmentEnabled: true,   // 是否显示排列按钮 相当于text-align
        uploadCallback: uploadImageCallBack,
        previewImage: true,
        inputAccept: 'image/*',
        alt: { present: false, mandatory: false, previewImage: true }
      },
    }}

  // onEditorStateChange={this.onEditorStateChange}
  />
}
export const richTextToHtml = (editorState) => {
  if (typeof editorState === 'string') {
    return editorState
  }
  if(typeof editorState ==='undefined'){
    return ''
  }
  return draftToHtml(convertToRaw(editorState.getCurrentContent()))
}
export default RichText